const db = require('../db/index')
const util = require('util')
const { string } = require('joi')
const query = util.promisify(db.query).bind(db)

function getTree(results, keyId) {
    // 获取一级菜单
    let arr = []
    for (idx in results) {
        if (results[idx].ps_level == 0) {
            if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                continue
            }
            arr.push({
                id: results[idx].ps_id,
                authName: results[idx].ps_name,
                path: results[idx].ps_api_path,
                pid: results[idx].ps_pid,
                children: []
            })
        }
    }
    //生成二级菜单
    for (idx in results) {
        if (results[idx].ps_level == 1) {
            for (var j = 0; j < arr.length; j++) {
                if (results[idx]['ps_pid'] == arr[j].id) {
                    if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                        continue
                    }
                    arr[j].children.push({
                        id: results[idx].ps_id,
                        authName: results[idx].ps_name,
                        path: results[idx].ps_api_path,
                        pid: results[idx].ps_pid,
                        children: []
                    })
                }
            }
        }
    }
    //生成三级菜单
    for (idx in results) {
        if (results[idx].ps_level == 2) {
            for (var j = 0; j < arr.length; j++) { //一级菜单
                var secondMenu = arr[j].children //二级菜单
                for (var i = 0; i < secondMenu.length; i++) { //找出二级菜单的每一项
                    if (results[idx]['ps_pid'] == secondMenu[i].id) {
                        if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                            continue
                        }
                        secondMenu[i].children.push({
                            id: results[idx].ps_id,
                            authName: results[idx].ps_name,
                            path: results[idx].ps_api_path,
                            pid: results[idx].ps_pid + ',' + arr[j].id
                        })
                    }
                }
            }
        }
    }
    return arr
}
exports.getPower = (req, res) => {
    // res.ResData("获取所有权限列表")
    //接受参数
    let type = req.params.type;
    // console.log(type);
    //判断参数类型
    if (!type || type != "list" && type != "tree") {
        return res.ResData("参数错误")
    }
    //根据参数操作数据库
    var sql = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    db.query(sql, (err, results) => {
        if (err) res.ResData("获取列表失败")
            // console.log(results);
        if (type == 'list') {
            var arr = []
            for (idx in results) {
                let result = results[idx];
                arr.push({
                    "id": result.ps_id,
                    "authName": result.ps_name,
                    "level": result.ps_level,
                    "pid": result.ps_pid,
                    "path": result.ps_api_path
                })
            }
            res.ResData("获取权限列表成功", 200, arr)
        } else {
            // let arr = []
            // for (idx in results) {
            //     if (results[idx].ps_level == 0) {
            //         arr.push({
            //             id: results[idx].ps_id,
            //             authName: results[idx].ps_name,
            //             path: results[idx].ps_api_path,
            //             pid: results[idx].ps_pid,
            //             children: []
            //         })
            //     }
            // }
            // //生成二级菜单
            // for (idx in results) {
            //     if (results[idx].ps_level == 1) {
            //         for (var j = 0; j < arr.length; j++) {
            //             if (results[idx]['ps_pid'] == arr[j].id) {
            //                 arr[j].children.push({
            //                     id: results[idx].ps_id,
            //                     authName: results[idx].ps_name,
            //                     path: results[idx].ps_api_path,
            //                     pid: results[idx].ps_pid,
            //                     children: []
            //                 })
            //             }
            //         }
            //     }
            // }
            // //生成三级菜单
            // for (idx in results) {
            //     if (results[idx].ps_level == 2) {
            //         for (var j = 0; j < arr.length; j++) { //一级菜单
            //             var secondMenu = arr[j].children //二级菜单
            //             for (var i = 0; i < secondMenu.length; i++) { //找出二级菜单的每一项
            //                 if (results[idx]['ps_pid'] == secondMenu[i].id) {
            //                     secondMenu[i].children.push({
            //                         id: results[idx].ps_id,
            //                         authName: results[idx].ps_name,
            //                         path: results[idx].ps_api_path,
            //                         pid: results[idx].ps_pid + ',' + arr[j].id
            //                     })
            //                 }
            //             }
            //         }
            //     }
            // }
            var arr = getTree(results, [])
            res.ResData("获取成功", 200, arr)
        }
    })
}

exports.rolesList = async(req, res) => {
    // res.ResData('111')
    //角色表里面查询角色
    var sql1 = "select * from sp_role"
    var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    try {
        var result2 = await query(sql2)
        var result1 = await query(sql1)
        let arr = []
        for (idx in result1) {
            let keyId = result1[idx]['ps_ids'].split(",");

            //获取一级菜单
            // let arr1 = []
            // for (i in result2) {
            //     if (result2[i].ps_level == 0) {
            //         //获取ps_id,判断ps_id在不在keyId这个数组里面
            //         //如果在数组里面，是角色里面的一级菜单，如果不在，什么也不要操作
            //         if (keyId.length !== 0 && keyId.indexOf(result2[i].ps_id + '') == -1) {
            //             continue
            //         }
            //         arr1.push({
            //             id: result2[i].ps_id,
            //             authName: result2[i].ps_name,
            //             path: result2[i].ps_api_path,
            //             pid: result2[i].ps_pid,
            //             children: []
            //         })
            //     }
            // }
            //获取二级菜单
            // for (i in result2) {
            //     if (result2[i].ps_level == 1) {
            //         for (var j = 0; j < arr1.length; j++) {
            //             if (result2[i]['ps_pid'] == arr1[j].id) {
            //                 if (keyId.length !== 0 && keyId.indexOf(result2[i].ps_id + '') == -1) {
            //                     continue
            //                 }
            //                 arr1[j].children.push({
            //                     id: result2[i].ps_id,
            //                     authName: result2[i].ps_name,
            //                     path: result2[i].ps_api_path,
            //                     pid: result2[i].ps_pid,
            //                     children: []
            //                 })
            //             }
            //         }
            //     }
            // }
            // console.log(keyId);
            let obj = {
                "id": result1[idx].role_id,
                "roleName": result1[idx].role_name,
                "roleDesc": result1[idx].role_desc,
                "children": []
            }
            let tree = getTree(result2, keyId)
            obj.children = tree;
            arr.push(obj)
        }
        res.ResData("获取角色列表成功", 200, arr)
            // console.log(arr);
    } catch (err) {
        res.ResData(err)
    }
}

//添加角色
exports.addRoles = (req, res) => {
        // res.ResData("添加角色")
        //1.获取数据
        // console.log(req.body);
        var role_name = req.body.roleName
        var role_desc = req.body.roleDesc
            //2.检查用户名是否存在
        var sql = "select * from sp_role where role_name=?"
        db.query(sql, role_name, (err, result) => {
            if (err) return res.ResData("添加失败!")
            if (result.length > 0) return res.ResData("用户名已存在!")
                //3.添加数据
            var sql = "insert into sp_role (role_name,role_desc)values(?,?)"
            db.query(sql, [role_name, role_desc], (err, data) => {
                if (err) return res.ResData("添加失败!")
                var sql = "select * from sp_role where role_name=?"
                db.query(sql, role_name, (err, result) => {
                    if (err) return res.ResData("获取信息失败!")
                    res.ResData("添加用户成功", 200, {
                        "roleId": result[0].role_id,
                        "roleName": role_name,
                        "roleDesc": role_desc
                    })
                })
            })
        })
    }
    //根据 ID 查询角色
exports.searchRoles = (req, res) => {
        // res.ResData("查询角色")
        //1.接收参数
        var id = req.params.id
            //2.查询用户信息
        var sql = "select * from sp_role where role_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData("角色查询失败!")
                //3.返回结果
            if (result.length > 0) {
                res.ResData("角色查询成功", 200, {
                    "roleId": result[0].role_id,
                    "roleName": result[0].role_name,
                    "roleDesc": result[0].role_desc
                })
            } else {
                res.ResData('用户查询失败')
            }
        })
    }
    //编辑提交角色
exports.updateRoles = (req, res) => {
        // res.ResData("编辑")
        //1.接收参数
        var id = req.params.id
        var roleName = req.body.roleName
        var roleDesc = req.body.roleDesc
            //2.更新数据
        var sql = "update sp_role set role_name=?, role_desc=? where role_id=?"
        db.query(sql, [roleName, roleDesc, id], (err, result) => {
            if (err) return res.ResData("更新角色信息失败!", err)
                // console.log(result);
            if (result.affectedRows < 1) return res.ResData("更新角色信息失败!")
            var sql = "select * from sp_role where role_id=?"
                //3.返回结果
            db.query(sql, id, (err, resResult) => {
                // console.log("object");
                // console.log(resResult);
                if (err) return res.ResData("信息读取失败", err)
                res.ResData("更新用户信息成功", 200, {
                    "id": resResult[0].mg_id,
                    "username": resResult[0].mg_name,
                    "role_id": resResult[0].role_id,
                    "mobile": resResult[0].mg_mobile,
                    "email": resResult[0].mg_email
                })
            })
        })
    }
    //删除角色
exports.deleteRoles = (req, res) => {
    // res.ResData("删除角色")
    var id = req.params.id
    var sql = "delete from sp_role where role_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return ResData("删除角色失败!")
        if (result.affectedRows != 1) return ResData("删除角色失败!")
        res.ResData("删除成功", 200)
    })
}
exports.updataRoleRight = (req, res) => {
    // req.ResData("角色授权")
    const roleId = req.params.roleId;

    if (roleId.trim() == "") return res.ResData("不能为空")
        // if ((parseInt(roleId) != roleId)) return res.ResData("角色id必须为整数")
    if (roleId.indexOf('.') != -1) return res.ResData("角色id必须是整字")
    if (parseInt(roleId) != roleId) return res.ResData("角色id必须是数字")
        // 处理逻辑
    var sql = "update sp_role set ps_ids=? where role_id=?"
    db.query(sql, [req.body.rids, roleId], (err, result) => {
        if (err) return res.ResData(err)
        res.ResData("更新成功", 200)
    })
}
exports.Roledelete = async(req, res) => {
    // res.ResData("asd")
    const roleId = req.params.roleId;
    const rightId = req.params.rightId;

    if (roleId.trim() == "") return res.ResData("不能为空")
        // if ((parseInt(roleId) != roleId)) return res.ResData("角色id必须为整数")
    if (roleId.indexOf('.') != -1) return res.ResData("角色id必须是整字")
    if (parseInt(roleId) != roleId) return res.ResData("角色id必须是数字")
    if (rightId.trim() == "") return res.ResData("不能为空")
        // if ((parseInt(roleId) != roleId)) return res.ResData("角色id必须为整数")
    if (rightId.indexOf('.') != -1) return res.ResData("权限id必须是整字")
    if (parseInt(rightId) != rightId) return res.ResData("权限id必须是数字")

    var sql = "select * from sp_role where role_id=?"

    // try {
    //     var result = await query(sql, roleId);
    //     ps_ids = result[0].ps_ids.split(',')
    //     new_ps_ids = []
    //     for (idx in ps_ids) {
    //         ps_id = ps_ids[idx];
    //         if (rightId == ps_id) {
    //             continue
    //         }
    //         new_ps_ids.push(ps_id)
    //     }
    //     // console.log(new_ps_ids)
    //     news_ps_ids = new_ps_ids.join(',');
    //     var updateSql = "update sp_role set ps_ids=? where role_id=?"
    //     var result2 = await query(updateSql, [new_ps_ids, roleId]);
    //     var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    //     var data = await query(sql2);
    //     var tree = getTree(data, news_ps_ids);
    //     // console.log(data)
    //     res.ResData(tree)
    // } catch {
    //     res.ResData("删除失败");
    // }

    db.query(sql, roleId, (err, result) => {
        if (err) return res.ResData("获取角色信息失败");
        ps_ids = result[0].ps_ids.split(',');
        new_ps_ids = []
        for (idx in ps_ids) {
            ps_id = ps_ids[idx];
            if (rightId == ps_id) {
                continue
            }
            new_ps_ids.push(ps_id)
        }
        // console.log(new_ps_ids)
        news_ps_ids = new_ps_ids.join(',');
        // 更新数据
        var sql = "update sp_role set ps_ids=? where role_id=?"
        db.query(sql, [news_ps_ids, roleId], (err, result) => {
            if (err) res.ResData("删除失败");
            // res.ResData("删除成功")
            var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
            db.query(sql2, (err, data) => {

                    var tree = getTree(data, news_ps_ids);
                    // console.log(data)
                    res.ResData(tree)
                })
                // console.log(data)
        })
    })
}